package repository

import (
	"context"
	"jk-time/webook/reward/cache"
	"jk-time/webook/reward/dao"
	"jk-time/webook/reward/domain"
)

type RewardRepository interface {
	SetCachedCodeURL(ctx context.Context, cu domain.CodeURL, r domain.Reward) error
	GetCachedCodeURL(ctx context.Context, r domain.Reward) (domain.CodeURL, error)
	SetCacheAccount(ctx context.Context, biz string, bizId int64) error
	Varify(ctx context.Context, biz string, bizId int64) bool

	CreateReward(ctx context.Context, reward domain.Reward) (int64, error)
	GetReward(ctx context.Context, rid int64) (domain.Reward, error)
	CachedCodeURL(ctx context.Context, cu domain.CodeURL, r domain.Reward)
	UpdateReward(ctx context.Context, rid int64, status domain.RewardStatus) error
}
type rewardRepository struct {
	dao   dao.RewardDao
	cache cache.Cache
}

func (r *rewardRepository) CreateReward(ctx context.Context, reward domain.Reward) (int64, error) {
	return r.dao.CreateReward(ctx, r.toEntity(reward))
}
func (repo *rewardRepository) GetReward(ctx context.Context, rid int64) (domain.Reward, error) {
	r, err := repo.dao.GetReward(ctx, rid)
	if err != nil {
		return domain.Reward{}, err
	}
	return repo.toDomain(r), nil
}
func (repo *rewardRepository) GetCachedCodeURL(ctx context.Context, r domain.Reward) (domain.CodeURL, error) {
	return repo.cache.GetCachedCodeURl(ctx, r)
}
func (repo *rewardRepository) SetCachedCodeURL(ctx context.Context, cu domain.CodeURL, r domain.Reward) error {
	return repo.cache.SetCachedCodeURL(ctx, cu, r)
}

func (repo *rewardRepository) UpdateReward(ctx context.Context, rid int64, status domain.RewardStatus) error {
	return repo.dao.UpdateStatus(ctx, rid, status.AsUint8())
}
func (repo *rewardRepository) toEntity(r domain.Reward) dao.Reward {
	return dao.Reward{
		Status:    r.Status.AsUint8(),
		Biz:       r.Biz,
		BizName:   r.BizName,
		BizId:     r.BizId,
		TargetUid: r.TargetUid,
		Uid:       r.Uid,
		Amt:       r.Amt,
	}
}
func (repo *rewardRepository) toDomain(r dao.Reward) domain.Reward {
	return domain.Reward{
		Id:        r.Id,
		Uid:       r.Uid,
		TargetUid: r.TargetUid,
		BizName:   r.BizName,
		Biz:       r.Biz,
		BizId:     r.BizId,
		Amt:       r.Amt,
		Status:    domain.RewardStatus(r.Status),
	}
}
